<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/4/19
 * Time: 14:36
 */

namespace app\mini\controller;


use app\company\model\StoreUser;
use app\service\traits\model\Sms;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Response;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WeChat\Oauth;
use app\mini\model\StoreUserOauth;
use WeMini\Crypt;

class Login extends Base
{

    private StoreUser $model;

    use Sms;


    public function initialize()
    {
        parent::initialize();
        $this->model = new StoreUser();
    }

    /**
     * 登录 此处对验证码进行了格外的处理 2 手机-密码-验证码
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws InvalidResponseException
     * @throws LocalCacheException
     */
    public function login(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene("login")->check($param);

        //验证码
//        if (!env('APP_DEBUG', false)) {
//            if (!captcha_check($param['code'], $param['code_id'])) return $this->error("验证码错误");
//        }

        $info = $this->model->gs($this->company_id)->where('mobile', $param['mobile'])->find();
        if (!$info) return $this->error("用户不存在");
        if (md5(request()->param("password") . 'dt') != $info->password) return $this->error("用户或密码错误");

        if(!$this->saveWechatOpenId($info)){
            $this->error("微信授权失败,或当前手机号已绑定其他微信号");
        }
        $userInfo = $info->toArray();
        unset($userInfo['password']);
        $token = getToken($info->id, 1); // 生成JWT令牌
        return $this->success('成功', compact("userInfo", "token"));
    }

    //两种方式 1 手机-短信验证码
    public function loginMobile(): Response
    {
        $param = request()->param();

        validate($this->validateClass)->scene("login_mobile")->check($param);
        //验证码
//        if (!env('APP_DEBUG', false)) {
//            if (!$this->check($param['mobile'], 'login', $param['code'])) return $this->error("短信验证码错误");
//        }
        $info = $this->model->gs($this->company_id)->where('mobile', $param['mobile'])->find();
        if (!$info) return $this->error("用户不存在");

        if(!$this->saveWechatOpenId($info)){
            $this->error("微信授权失败,或当前手机号已绑定其他微信号");
        }

        $userInfo = $info->toArray();
        unset($userInfo['password']);
        $token = getToken($info->id, 1); // 生成JWT令牌
        // 更新登录信息
        return $this->success('成功', compact("userInfo", "token"));
    }


    /**
     * 发送短信验证码
     * @return Response
     * @throws InvalidArgumentException
     */
    public function sendSms(): Response
    {
        $param = request()->param();
        validate($this->validateClass)->scene("send_sms")->check($param);
        //短信码
        $code = rand(1000, 9999);
        //发送短信
        if (!$this->send(request()->param("mobile"), "login", $code)) {
            return $this->error("发送失败");
        }
        //存入redis
        cache("sms_login_" . $param['mobile'], $code, 10 * 60);
        if (!Cache::has('sms_' . $param['mobile'])) cache('sms_' . $param['mobile'], 1, config('sms.max_time'));//计数器 单位时间内只能发送N次
        Cache::inc('sms_' . $param['mobile'], 1);//计数器 单位时间内只能发送N次
        return $this->success("发送成功");
    }

    //保存微信第三方id
    public function saveWechatOpenId($info)
    {
        $config = getWxConfig(['appid' => $this->appid]);
        $wxCode = (new Crypt($config))->session(request()->param("wx_code", 0));
        if (!$wxCode) return false;

        if (!$openId = $info->storeUserOauths()->where('company_id',$info->company_id)->where('oauth_type', 1)->value('oauth_id')) {
            StoreUserOauth::create(['store_user_id' => $info->id, 'company_id' => $info->company_id, 'oauth_id' => $wxCode['openid'], 'oauth_type' => 1]);
            $openId = $wxCode['openid'];
        }

        if (!env('APP_DEBUG', false)) {
            if($openId != $wxCode['openid'])return false;
        }
    }

}